var Q = require('q'), 
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    badTypeBindController = require('../../../QC/server/controllers/BadTypeBind.server.controller');

//删除品质记录
exports.deleteQCRecords = function (bizRecordId, completeFun) {
    var entity = entityCollection.getEntity("QCRecord");
    entity.deleteByCondition({BizRecord: bizRecordId}, 
       function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '删除品质记录错误';
            newErr.message = '请检查删除参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

//删除品质记录
exports.deleteByStandarsNorm = function (qcStandard, qcNorm, bizRecord, completeFun) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("QCRecord");
    entity.deleteByCondition({ QCStandard: qcStandard, QCNorm: qcNorm, BizRecord: bizRecord}, 
       function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '删除品质记录错误';
            newErr.message = '请检查删除参数！';
            deferred.reject(newErr);
        } else {
            deferred.resolve(record);
        }
    });

    return deferred.promise;
};

//查找流水对应的所有品质记录
exports.findAllQCRecords = function (bizRecordId, completeFun) {
    
    var entity = entityCollection.getEntity("QCRecord");
    entity.find({BizRecord: bizRecordId}, null,
     null, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询品质记录错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

//通过条码流水ID查找品质记录集
exports.findQCRecordByBizRecordID = function(bizRecordId, completeFun){
    var entity = entityCollection.getEntity("QCRecord");
    entity.find({BizRecord: bizRecordId}, null,
        [
            {
                path: 'QCNorm',
                populate: {
                    path: 'ExtendEnum',
                    select: 'Code Name',
                    model: 'ExtendEnum'
                }
            },
            {path: 'QCStandard'}
        ], function(err, records){
        if(err){
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询品质记录错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
        }
        else{
            completeFun(null, records);
        }
    });
};

exports.findQCRecords = function (bizRecordId, completeFun) {
    var qcRecord = entityCollection.getEntity("QCRecord");
    qcRecord.Entity.find({
        BizRecord: bizRecordId
    }, { 
        BadPosition: 1, BadType: 1, Images: 1, Description: 1
    }).exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询品质记录错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
            return;
        }
        completeFun(null, records);
    });
};

// 循环缺陷集合，创建品质记录
exports.addQCRecords = function (bizRecordId,badRecords,completeFun) {
   var qcRecords = [];
   for (var i = 0; i < badRecords.length; i++) {
          qcRecords.push({
            BizRecord:bizRecordId,
            QCNorm:0,
            NormValue:'',
            BadType:badRecords[i].BadTypeValue,
            IsQualified:false,
            BadPosition:badRecords[i].BadPositionValue,
            Description:badRecords[i].Description
          });    
   };  

    var promises = [];
    qcRecords.forEach(function (qcRecord) {
        promises.push(queryQCNorm(qcRecord));   
    });
    
    Q.all(promises).then(function () {
        
        qcRecords.forEach(function (qcRecord) {
           qcRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
           qcRecord.CreatedBy = bizRecordId;//bizRecordId;
        });

        writeQCRecords(qcRecords).then(function(result) {
           completeFun(null, result);
        }, function(err) {
           var newErr = new Error();
           newErr.leval = 9;
           newErr.title = '创建品质记录失败';
           newErr.message = '';
           completeFun(newErr);
           
        });      
    });  
};

// 统计某段时间缺陷类型数
exports.getDurationBadTypes = function (startTime, endTime) {
    var deferred = Q.defer();

    var qcRecord = entityCollection.getEntity("QCRecord");
    qcRecord.aggregate([{
        $match: {
            CreatedOn: { $gte: startTime, $lte: endTime },
            BadType: { $ne: null}
        }
    }, {
        $group: {
            _id: { BadType: "$BadType" }, 
            count: { $sum: 1 }
        }
    }, {
        $project: {
            BadType: "$_id.BadType",
            count: 1,
            _id: 0
        }
    }], function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '统计缺陷类型失败';
            newErr.message = '统计缺陷类型数失败';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(records);
    });

    return deferred.promise;
};


function queryQCNorm (qcRecord) {
    var deferred = Q.defer();

    badTypeBindController.findQCNormIDByBadType(qcRecord.BadType, function (err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (result.QCNorm) {
            qcRecord.QCNorm = result.QCNorm._id;
        } 
        deferred.resolve();            
    });  

    return deferred.promise;
}

function writeQCRecords (qcRecords) {
    var deferred = Q.defer();

    Transaction.BatchSaveByTran([
            {EntityName: 'QCRecord', Records: qcRecords}
        ],
        function(err, result){
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(result);
        }
    );

    return deferred.promise;
}